<template>
  <el-card shadow="hover">
    <el-form inline>
      <el-form-item>
        <el-input
          placeholder="用户名"
          v-model="adminUserParams.username"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="getAdminUserList"
          >搜索</el-button
        >
        <el-button @click="handleReset">清空</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="showAdminUser">添加用户</el-button>
    <el-button type="danger">批量删除</el-button>
    <el-table border class="mt-20" :data="adminUserList" v-loading="loading">
      <el-table-column type="selection" width="60" align="center" />
      <el-table-column
        label="序号"
        type="index"
        width="60"
        align="center"
      ></el-table-column>
      <el-table-column label="用户名" prop="username"></el-table-column>
      <el-table-column
        label="用户昵称"
        prop="nickName"
        width="200"
      ></el-table-column>
      <el-table-column
        label="角色列表"
        prop="roleName"
        width="200"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        prop="gmtCreate"
        width="200"
      ></el-table-column>
      <el-table-column
        label="更新时间"
        prop="gmtModified"
        width="200"
      ></el-table-column>
      <el-table-column label="操作" width="200">
        <template v-slot="{ row }">
          <el-button
            type="info"
            size="small"
            :icon="User"
            @click="showAssignRole(row)"
            v-if="userInfoStore.buttons.includes('btn.User.assgin')"
          />
          <el-button
            type="warning"
            size="small"
            :icon="Edit"
            @click="updateAdminUser(row)"
            v-if="userInfoStore.buttons.includes('btn.User.update')"
          />
          <el-popconfirm
            :icon="InfoFilled"
            icon-color="#626AEF"
            :title="`您确定要删除${addOrUpdateAdminUserData.username}吗？`"
            @confirm="deleteAdminUser(row.id)"
            v-if="userInfoStore.buttons.includes('btn.User.remove')"
          >
            <template #reference>
              <el-button type="danger" size="small" :icon="Delete" />
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="mt-20"
      v-model:current-page="adminUserParams.currentPage"
      v-model:page-size="adminUserParams.pageSize"
      :page-sizes="[3, 6, 9, 12]"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      @size-change="getAdminUserList"
      @current-change="getAdminUserList"
    />

    <!-- 添加用户对话框 -->
    <el-dialog
      v-model="addOrUpdateAdminUserVisible"
      :title="`${addOrUpdateAdminUserData.id ? '修改' : '添加'}用户`"
    >
      <el-form
        label-width="100px"
        ref="addOrUpdateAdminUserRef"
        :model="addOrUpdateAdminUserData"
        :rules="addOrUpdateAdminUserRules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="addOrUpdateAdminUserData.username"
            placeholder="用户名"
          />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input
            v-model="addOrUpdateAdminUserData.nickName"
            placeholder="用户昵称"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="addOrUpdateAdminUserData.password"
            placeholder="密码"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addOrUpdateAdminUserVisible = false">取消</el-button>
        <el-button type="primary" @click="addOrUpdateAdminUser">保存</el-button>
      </template>
    </el-dialog>

    <!-- 分配用户角色 -->
    <el-dialog v-model="assignAdminUserRoleVisible" title="分配用户角色">
      <el-form
        label-width="100px"
        ref="assignRoleFormRef"
        :model="assignRoleFormData"
        :rules="assignRoleFormRules"
      >
        <el-form-item label="用户名">
          <el-input
            placeholder="用户名"
            disabled
            v-model="assignRoleFormData.username"
          />
        </el-form-item>
        <el-form-item label="角色列表" prop="roleId">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <el-checkbox-group
            v-model="assignRoleFormData.roleId"
            @change="handleCheckedRolesChange"
          >
            <el-checkbox
              v-for="role in allRolesList"
              :key="role.id"
              :label="role.id"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="assignRole">保存</el-button>
          <el-button @click="assignAdminUserRoleVisible = false"
            >取消</el-button
          >
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "XUser",
};
</script>

<script lang="ts" setup>
import {
  Search,
  User,
  Edit,
  Delete,
  InfoFilled,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import type { CheckboxValueType } from "element-plus";
import { ref, reactive, onMounted } from "vue";
import {
  GetAdminUserListApi,
  AddAdminUserApi,
  UpdateAdminUserApi,
  DeleteAdminUserApi,
  GetRoleByUserIdApi,
  AssignRoleApi,
} from "@/api/acl/user";
import type {
  UserItemsList,
  AddOrUpdateAdminUserFormData,
  UserItems,
  RoleList,
} from "@/api/acl/model/userModel";
import { useUserInfoStore } from "@/stores/userInfo";

const userInfoStore = useUserInfoStore();

/*************** 用户列表数据展示 ****************/
const adminUserParams = reactive({
  pageSize: 3,
  currentPage: 1,
  username: "",
});

const total = ref(0);
const adminUserList = ref<UserItemsList>([]);
const loading = ref(false);

const getAdminUserList = async () => {
  loading.value = true;
  const res = await GetAdminUserListApi({
    page: adminUserParams.currentPage,
    limit: adminUserParams.pageSize,
    username: adminUserParams.username,
  });
  adminUserList.value = res.items;
  total.value = res.total;
  loading.value = false;
};

// onMounted(() => {
//   getAdminUserList();
// });
onMounted(getAdminUserList);

// 清空
const handleReset = () => {
  adminUserParams.username = "";
  getAdminUserList();
};

/*************** 添加用户 ****************/
const addOrUpdateAdminUserVisible = ref(false);

const addOrUpdateAdminUserRef = ref();
const addOrUpdateAdminUserData = reactive<AddOrUpdateAdminUserFormData>({
  id: undefined,
  username: "",
  nickName: "",
  password: "",
});
const addOrUpdateAdminUserRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  nickName: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

// 点击添加用户按钮
const showAdminUser = () => {
  addOrUpdateAdminUserVisible.value = true;
  addOrUpdateAdminUserData.username = "";
  addOrUpdateAdminUserData.nickName = "";
  addOrUpdateAdminUserData.password = "";
  addOrUpdateAdminUserRef.value?.clearValidate();
};

// 点击保存按钮
const addOrUpdateAdminUser = async () => {
  await addOrUpdateAdminUserRef.value.validate();
  const id = addOrUpdateAdminUserData.id;
  if (id) {
    await UpdateAdminUserApi({ ...addOrUpdateAdminUserData, id });
  } else {
    await AddAdminUserApi(addOrUpdateAdminUserData);
  }
  getAdminUserList();
  addOrUpdateAdminUserVisible.value = false;
  ElMessage.success(`${id ? "修改" : "添加"}用户成功！`);
};

/*************** 修改用户 ****************/
const updateAdminUser = (row: UserItems) => {
  addOrUpdateAdminUserVisible.value = true;
  addOrUpdateAdminUserData.id = row.id;
  addOrUpdateAdminUserData.username = row.username;
  addOrUpdateAdminUserData.nickName = row.nickName;
  addOrUpdateAdminUserData.password = "";
  addOrUpdateAdminUserRef.value?.clearValidate();
};

/*************** 删除用户 ****************/
const deleteAdminUser = async (id: string) => {
  await DeleteAdminUserApi(id);
  ElMessage.success("删除用户成功！");
  getAdminUserList();
};

/*************** 分配用户角色 ****************/
const checkAll = ref(false); // 全选&全不选
const isIndeterminate = ref(false); // 半选
const allRolesList = ref<RoleList>([]);

// 全选&全不选
const handleCheckAllChange = (val: CheckboxValueType) => {
  if (val) {
    // 全选
    assignRoleFormData.roleId = allRolesList.value.map(
      (allRoles) => allRoles.id
    );
  } else {
    // 全不选
    assignRoleFormData.roleId = [];
  }
  // 取消半选
  isIndeterminate.value = false;
};

const handleCheckedRolesChange = () => {
  if (!assignRoleFormData.roleId.length) {
    // 全不选
    isIndeterminate.value = false;
    checkAll.value = false;
  } else if (assignRoleFormData.roleId.length === allRolesList.value.length) {
    // 全选
    isIndeterminate.value = false;
    checkAll.value = true;
  } else {
    // 半选
    isIndeterminate.value = true;
  }
};

// 显示分配用户角色列表
const showAssignRole = async (row: UserItems) => {
  assignAdminUserRoleVisible.value = true;
  assignRoleFormData.userId = row.id;
  assignRoleFormData.username = row.username;
  assignRoleFormData.roleId = [];
  assignRoleFormRef.value?.clearValidate();

  const res = await GetRoleByUserIdApi(row.id);
  allRolesList.value = res.allRolesList;
  assignRoleFormData.roleId = res.assignRoles.map(
    (assignRole) => assignRole.id
  );
  // 解决半选bug
  handleCheckedRolesChange();
};

const assignAdminUserRoleVisible = ref(false);
const assignRoleFormRef = ref();
const assignRoleFormData = reactive<{
  userId: string;
  roleId: string[];
  username: string;
}>({
  userId: "",
  roleId: [],
  username: "",
});
const assignRoleFormRules = reactive({
  roleId: [
    {
      required: true,
      message: "请至少选择一个角色",
    },
  ],
});

// 按下保存按钮
const assignRole = async () => {
  await assignRoleFormRef.value.validate();
  await AssignRoleApi(assignRoleFormData.userId, assignRoleFormData.roleId);
  ElMessage.success("分配角色成功！");
  getAdminUserList();
  assignAdminUserRoleVisible.value = false;
};
</script>

<style scoped></style>
